package com.etoak.controller;


import cn.hutool.core.io.file.FileNameUtil;
import cn.hutool.core.util.IdUtil;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

@RestController
public class UploadController {

    public static final String JPG = "image/jpeg";

    public static final String PNG ="image/png";

    /**
     * 图片上传接口
     * 接口地址：localhost:8080/upload
     * 请求方法：Post
     * 请求参数：file
     * 请求参数类型：multipart/form-data
     * 响应结果
     */
    @PostMapping(value = "/upload",produces = "text/plain;charset=utf-8")
    public String upload(MultipartFile file) throws IOException {
        /** 判断文件是否为空 */
        if(ObjectUtils.isEmpty(file) || file.isEmpty()){
            return "文件不能为空";
        }

        /**判断图片的类型 */
        String contentype = file.getContentType();
        if(!StringUtils.equalsAny(contentype,JPG,PNG)){
            return "仅支持jpg和png格式图片";
        }

        /**修改文件名称 */
        // 文件扩展名 png
        String extension = FilenameUtils.getExtension(file.getOriginalFilename());
        String uuid = IdUtil.simpleUUID();
        String filename = StringUtils.join(uuid,".",extension);

        /* 创建上传目录*/
        File uploadDir = new File("d:/upload/et2205");
        if(!uploadDir.exists()){
            uploadDir.mkdirs();
        }

        //创建目标文件
        File desFile = new File(uploadDir,filename);

        //上传
        file.transferTo(desFile);

        String path = "/pics/" + filename;
        return path;
    }
}
